package com.byit.shrio.filter;

import com.alibaba.fastjson.JSON;
import com.byit.enums.PromptInfo;
import com.byit.msg.MessageResult;
import com.byit.shrio.session.SessionHelper;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * shiro登录状态校验
 *
 * @author marker
 **/
public class ShiroLoginFilter implements Filter {


    /**
     * 排除登录校验的地址
     */
    String[] jumpUrls = new String[]{
            "/api/login",
            "/api/login/out",
            "/api/upload/carouselImages",
            "/api/upload/images",
            "/api/upload/avatars",
            "/api/upload/video",
            "/api/upload/images/goods",
            "/api/upload/newsImages",
            "/api/upload/appPublish",
            "/api/sys/sysAppVersion/upload",
            "/api/sys/appMail/send",
            "/monitoring",
            "/api/ueditor/config",
            "/quartz/*",
            "/test/*",
            "/api/sys/sysCompany/selectAll",
            "/ws/*"
    };

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        ServletContext servletContext = httpServletRequest.getServletContext();
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        //创建subject，其实创建的是Subject的代理类DelegatingSubject

        HttpSession session = httpServletRequest.getSession(false);


        String uri = httpServletRequest.getRequestURI();
        Long userId = SessionHelper.getUserId(session);

        // 跨域请求
        if ("OPTIONS".equals(httpServletRequest.getMethod())) {
            httpServletResponse.getWriter().write("");
            return;
        }

        if (userId == null && !ArrayUtils.contains(jumpUrls, uri)) {
            if (StringUtils.isNotEmpty(uri) && uri.startsWith("/api")) { // 如果是ajax返回指定数据
                httpServletResponse.setCharacterEncoding("UTF-8");
                httpServletResponse.setContentType("application/json");
                httpServletResponse.getWriter().write(
                        JSON.toJSONString(MessageResult.warpper(PromptInfo.USER_LOGIN_INVALID))
                );
                return;
            }
        }
        chain.doFilter(request, response);
    }

    @Override
    public void destroy() {

    }
}